package com.yunxitest.yunxitest

import android.graphics.Color
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.TextView
import com.yunxitest.yunxitest.Interface.IDetectItem
import com.yunxitest.yunxitest.Interface.IResultCallback
import com.yunxitest.yunxitest.item.audio.AudioDetectManager
import com.yunxitest.yunxitest.item.ethernet.EthernetDetectManager
import com.yunxitest.yunxitest.item.hdmi.Hdmi1Camera
import com.yunxitest.yunxitest.item.hdmi.Hdmi2Camera
import com.yunxitest.yunxitest.item.info.SysInfoDetectManager
import com.yunxitest.yunxitest.item.light.LightDetectManager
import com.yunxitest.yunxitest.item.sim.SimDetectManager
import com.yunxitest.yunxitest.item.storage.SdCardManager
import com.yunxitest.yunxitest.item.storage.USBStorageManager
import com.yunxitest.yunxitest.item.typec.TypecDetectManager
import com.yunxitest.yunxitest.item.wifi.WifiDetectManager
import com.yunxitest.yunxitest.utils.L
import com.yunxitest.yunxitest.utils.T
import com.yunxitest.yunxitest.utils.TestLog
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*


class MainActivity : AppCompatActivity() {
    private var isRunNext = true
    var timer :Timer?=null

    /**
     *  待检测项目列表
     */
    private val ITEM_HDMI1_INDEX = 0
    private val ITEM_HDMI2_INDEX = 1
    private val ITEM_BOOT_BUTTON_INDEX = 2
    private val ITEM_RESET_BUTTON_INDEX = 3
    private val ITEM_AUDIO_INDEX = 0
    private val ITEM_WIFI_INDEX = 1
    private val ITEM_SIM_INDEX = 2
    private val ITEM_ETHERNET_INDEX = 3


    data class Item(var detectItem: IDetectItem?, var result: IResultCallback?, var textView: TextView,
                    var isAutoDetect: Boolean = true, var isAutoSuccess: Boolean = false)

    private var currentIndex = 0
    private var lastIndex = 0

    private var list = ArrayList<Item>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        TestLog.writeLog("[HEAD]")
        initView()
        initData()

    }


    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
    }

    private fun initData() {
        TestLog.writeLog("[TEST DATA]")
        // hdmi1
        val r1 = ResultCallback()
        val item1 = Item(Hdmi1Camera(this, r1), r1, findViewById(R.id.tv_hdmi1))
        list.add(item1)

        //hdmi2
        val r2 = ResultCallback()
        val item2 = Item(Hdmi2Camera(this, r2), r2, findViewById(R.id.tv_hdmi2))
        list.add(item2)

        // sim
        val r3 = ResultCallback()
        val item3 = Item(SimDetectManager(this,r3), r3, findViewById(R.id.tv_sim), true, false)
        list.add(item3)

        // wifi
        val r4 = ResultCallback()
        val item4 = Item(WifiDetectManager(this, r4), r4, findViewById(R.id.tv_wifi), true, false)
        list.add(item4)

        // info
        val r5 = ResultCallback()
        val item5 = Item(SysInfoDetectManager(this, r5), null, findViewById(R.id.tv_info), true)
        list.add(item5)

        // light
        val item6 = Item(LightDetectManager(), null, findViewById(R.id.tv_light), false)
        list.add(item6)

        // u盘    // todo     isAutoSuccess = false
        val r7 = ResultCallback()
        val item7 = Item(USBStorageManager(this,r7), r7, findViewById(R.id.tv_u), true, false)
        list.add(item7)

        // audio in
//        val r8 = ResultCallback()
        val item8 = Item(AudioDetectManager(null), null, findViewById(R.id.tv_audio_in), false, false)
        list.add(item8)

        // audio out
        val item9 = Item(null, null, findViewById(R.id.tv_audio_out), false, false)
        list.add(item9)

        // lcm
        val item10 = Item(null, null, findViewById(R.id.tv_lcm), false, false)
        list.add(item10)

        // boot button
        val r11 = ResultCallback()
        val item11 = Item(null, null, findViewById(R.id.tv_boot_button), true, true)
        list.add(item11)

        // volume button
        val item12 = Item(null, null, findViewById(R.id.tv_reset_button), false, false)
        list.add(item12)

        // sdcard
        val r13 = ResultCallback()
        val item13 = Item(SdCardManager(this,r13), r13, findViewById(R.id.tv_sdcard), true, false)
        list.add(item13)

        // ethernet
        val r14 = ResultCallback()
        val item14 = Item(EthernetDetectManager(this, r14), r14, findViewById(R.id.tv_ethernet), true, false)
        list.add(item14)

        //type c1
        val r15 = ResultCallback()
        val item15 = Item(TypecDetectManager(this, r15), r15, findViewById(R.id.tv_typec1), true, false)
        list.add(item15)

        //type c2
        val r16 = ResultCallback()
        val item16 = Item(null, null, findViewById(R.id.tv_typec2), false, false)
        list.add(item16)

        // screen out
        val item17 = Item(null, null, findViewById(R.id.tv_screen_out), false, false)
        list.add(item17)

    }

    private fun initView() {
        findViewById<TextView>(R.id.tv_start_detect).setOnClickListener {
            if(tv_start_detect.text == "退出程序"){
//                restoreDefaultState()
                finish()
                return@setOnClickListener
            }
            var task:TestTask=TestTask()
            timer=Timer()
            timer?.schedule(task, 0, 1000)
            it.visibility = View.GONE
            ll_bottom.visibility = View.VISIBLE
        }

        tv_success.setOnClickListener {
            showResult(true)
            isRunNext = true
        }

        tv_fail.setOnClickListener {
            showResult(false)
            isRunNext = true
        }
    }


    inner class TestTask: TimerTask() {
        internal var index = 0
        override fun run() {
            if (isRunNext) {
                if (index >= list.size) {
                    L.d("testItem", " ###  detect finish .")

                    this.cancel()
                    return
                }
                isRunNext = false
                lastIndex = index - 1
                if (lastIndex >= 0) {
                    if (index == 8) {   // wait audio out detect finish
                        list[7].detectItem?.finish()
                    } else if (index == 7) {
                        // do nothing
                    } else {
                        list[lastIndex].detectItem?.finish()
                    }
                } else {
                    lastIndex = 0
                }
                currentIndex = index
                if (list[index].isAutoSuccess) {   // 默认成功
                    showResult(true)
                    isRunNext = true
                    L.d("testItem", "start detect item ------------------->  ### index  :   $index")
                } else {
                    showDetecting(index)
                    if (list[index].isAutoDetect) {
                        showBottomAutoDetecting()
                    } else {
                        if(index==15){
                            runOnUiThread{
                                T.showShort(this@MainActivity,"请反插type-c")
                            }
                        }
                        showBottomButton()
                    }
                    list[index].detectItem?.startDetect()
                    L.d("testItem", "start detect item ------------------->  ### index  :   $index")
                }
                index++
            }
        }
    }

    fun restoreDefaultState(){
        for(i in list.indices){
            var text = list[i].textView.text
            text = text.substring(0, text.length - 2)
            text+="待检测"
            list[i].textView.text = text
            list[i].textView.setTextColor(Color.WHITE)
        }
    }

    inner class ResultCallback : IResultCallback {
        override fun success() {
            showResult(true)
            isRunNext = true
        }

        override fun fail(reason: String?) {
            showResult(false)
            isRunNext = true
        }
    }

    private fun showResult(isSucess: Boolean) {
        runOnUiThread {
            if (currentIndex == list.size) {
                currentIndex -= 1
            }
            L.d("testItem", " show result :   $isSucess")
            var text = list[currentIndex].textView.text
            text = text.substring(0, text.length - 3)
            if (isSucess) {
                text += " 成功"
                list[currentIndex].textView.setTextColor(Color.GREEN)
                TestLog.writeLog("${(currentIndex+1)}=P")
            } else {
                text += " 失败"
                list[currentIndex].textView.setTextColor(Color.RED)
                TestLog.writeLog("${(currentIndex+1)}=F")
            }
            list[currentIndex].textView.text = text
            if(currentIndex==16){
                timer?.cancel()
                timer?.purge()
                timer=null
                showReCheckBottomButton()
                writeResult()
            }
        }
    }

    private fun writeResult() {
        TestLog.writeLog("[TEST_RESULT]")
        var isPass=true
        for(i in list.indices){
            var text = list[i].textView.text
            text = text.substring(text.length - 2,text.length)
            if(text == "成功"){
//                TestLog.writeLog("$currentIndex=F")
            }else{
                isPass=false
                TestLog.writeLog("Error_Code=E"+(i+1))
            }

        }
        if(isPass){
            TestLog.writeLog("Test_Result=PASS")
        }else{
            TestLog.writeLog("Test_Result=FAIL")
        }
    }

    private fun showDetecting(index: Int) {
        runOnUiThread {
            var text = list[index].textView.text
            text = text.substring(0, text.length - 3)
            text += " 检测中"
            list[index].textView.setTextColor(Color.BLUE)
            list[index].textView.text = text
        }
    }

    private fun showBottomAutoDetecting() {
        runOnUiThread {
            val bottom = findViewById<TextView>(R.id.tv_start_detect)
            bottom.isClickable=false
            bottom.visibility = View.VISIBLE
            bottom.text = "第" + (currentIndex + 1) + "项自动检测中..."
            ll_bottom.visibility = View.GONE
        }
    }

    private fun showBottomButton() {
        runOnUiThread {
            val bottom = findViewById<TextView>(R.id.tv_start_detect)
            bottom.visibility = View.GONE
            bottom.text = "开始检测"
            ll_bottom.visibility = View.VISIBLE
        }
    }

    private fun showReCheckBottomButton() {
        runOnUiThread {
            val bottom = findViewById<TextView>(R.id.tv_start_detect)
            bottom.visibility = View.VISIBLE
            bottom.text = "退出程序"
            bottom.isClickable=true
            ll_bottom.visibility = View.GONE
        }
    }

}
